package com.example.controller;

import com.example.common.Result;
import com.example.service.PermissionInitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 权限初始化控制器
 * 用于手动触发权限和角色的初始化
 */
@Slf4j
@RestController
@RequestMapping("/api/permission-init")
@CrossOrigin
public class PermissionInitController {
    
    @Autowired
    private PermissionInitService permissionInitService;
    
    /**
     * 初始化基础权限和角色
     */
    @PostMapping("/init-basic")
    public Result<String> initBasicPermissions() {
        try {
            permissionInitService.initializeBasicPermissions();
            log.info("基础权限和角色初始化成功");
            return Result.success("基础权限和角色初始化成功");
        } catch (Exception e) {
            log.error("基础权限和角色初始化失败", e);
            return Result.error("初始化失败：" + e.getMessage());
        }
    }
    
    /**
     * 检查并创建缺失的权限
     */
    @PostMapping("/check-missing")
    public Result<String> checkMissingPermissions() {
        try {
            permissionInitService.checkAndCreateMissingPermissions();
            log.info("权限检查和创建完成");
            return Result.success("权限检查和创建完成");
        } catch (Exception e) {
            log.error("权限检查失败", e);
            return Result.error("权限检查失败：" + e.getMessage());
        }
    }
    
    /**
     * 为当前用户创建基础权限
     */
    @PostMapping("/create-user-permissions/{userId}")
    public Result<String> createUserPermissions(@PathVariable Long userId) {
        try {
            permissionInitService.createBasicUserPermissions(userId);
            log.info("为用户 {} 创建基础权限成功", userId);
            return Result.success("用户权限创建成功");
        } catch (Exception e) {
            log.error("为用户 {} 创建权限失败", userId, e);
            return Result.error("用户权限创建失败：" + e.getMessage());
        }
    }
} 